/**
 * Created by Ysssssss on 2021/5/28.
 */

import React, { useState, useEffect } from 'react'
import dayjs from "dayjs";

const CountdownByTargetTime = props => {
    const { targetTime } = props
    const [ countdownTimeStr, setCountdownTimeStr ] = useState('')

    useEffect(() => {
        let action = () => {
            let minutes = dayjs(targetTime).diff(dayjs(), 'minute')
            let days = Math.floor(minutes / (60 * 24))
            minutes = minutes - days * 60 * 24
            let hours = Math.floor(minutes / 60)
            minutes = minutes - hours * 60
            setCountdownTimeStr(`${days ? `${days}天` : ''}${(days || hours) ? `${hours}时` : ''}${minutes}分钟`)
        }
        let countdownTimer = setInterval(action, 60*1000)
        action()
        return () => {
            countdownTimer && clearInterval(countdownTimer)
        }
    }, [targetTime])

    return countdownTimeStr
}

export default CountdownByTargetTime